package cjyyp.controller;

import cjyyp.entity.User;
import cjyyp.service.IUserService;
import cjyyp.utils.RespBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author cjyyp
 * @since 2023-03-12
 */
@RestController
@Api(tags = "用户管理")
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @GetMapping("testCodeTransaction")
    @ApiOperation("测试编程式事务")
    public RespBean<List<User>> list1(){
        RespBean<List<User>> result = transactionTemplate.execute(new TransactionCallback<RespBean<List<User>>>() {
            @Override
            public RespBean<List<User>> doInTransaction(TransactionStatus transactionStatus) {
                userService.save(new User("11", "sgf", "10101010", "ss", "ss", "ss", 1, LocalDateTime.now(), LocalDateTime.now()));
                System.out.println(10/0);
                return RespBean.success(userService.list());
            }
        });
        return result;
    }
    @GetMapping("testAnnotationTransaction")
    @ApiOperation("再测试编程式事务是否失效")
    @Transactional(rollbackFor = Exception.class)
    public RespBean list2(){
        boolean save = userService.save(new User("11", "sgf", "10101010", "ss", "ss", "ss", 1, LocalDateTime.now(), LocalDateTime.now()));
        System.out.println(10/0);
        return RespBean.success(save);
    }

    @GetMapping("kafkaProducer")
    @ApiOperation("向Kafka的first主题发生一条消息")
    public RespBean<SendResult<String, String>> kafkaProducer(){
        User user = userService.list().get(0);
        try {
            kafkaTemplate.send(new ProducerRecord<String, String>("first", user.toString()));
        } catch (Exception e) {
            RespBean.error();
        }
        return RespBean.success();
    }

}
